<?php

class NCore_SQLDatasource implements NCore_IDatasource
{
	private $dsn;
	private $password;
	private $username;
	private $inputs = array();
	private $results;
	private $name;

	function __construct($name = NULL)
	{
		$this->name = $name;
		$this->dsn = N::config('sql_datasource_dsn');
		$this->username = N::config('sql_datasource_username');
		$this->password = N::config('sql_datasource_password');
	}
	public function withDSN($dsn)
	{
		$this->dsn = $dsn;
		return $this;
	}
	public function withUsername($username)
	{
		$this->username = $username;
		return $this;
	}
	public function withPassword($password)
	{
		$this->password = $password;
		return $this;
	}
	public function withQuery($query)
	{
		$this->query = $query;
		return $this;
	}
	public function withInputs($inputs)
	{
		$this->inputs = $inputs;
		return $this;
	}
	protected function getConnection()
	{	
		if(is_null($this->dsn) || is_null($this->username) || is_null($this->password))
		{
			throw new Exception('The SQLDatasource \''.$this->name.'\' has a null value for dsn, username, or password and cannot connect to the database.  Values can be set explicitly on this particular SQLDatasource, or defaults can be set in the config file.');
		}
	
		$dbh = new PDO($this->dsn, $this->username, $this->password);
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		
		return $dbh;
	}
	protected function getInputValues()
	{
		foreach($this->inputs as $key=>$value)
		{
            if($value instanceof NCore_IValue)
			{
				$this->inputs[$key] = $value->getValue();
			}
		}
	}
	public function getDataset()
	{
        if(!is_null($this->results))
            return $this->results;

		$this->getInputValues();
		$this->results = new NCore_Dataset();
		$dbh = $this->getConnection();
		$stmt = $dbh->prepare($this->query);
		
		if($stmt->execute($this->inputs))
		{
			while($row = $stmt->fetch(PDO::FETCH_NAMED))
			{				
				$this->results[] = new NCore_Row($row);
			}

            $dbh = NULL;
			return $this->results;
		}
		else
		{
			throw new Exception('The query in the \''.$this->name.'\' SQLDatasource could not be completed.');
		}
	}
}

?>